import React, { useEffect, useCallback, useState, useMemo } from 'react';
import { CircularProgress, Box, Button, Drawer, TextField, InputAdornment, IconButton, Stack } from '@mui/material';  //
import Grid from '@mui/material/Grid2';     //    ContentCopyOutlined, ContentPaste,  ,  MRT_ActionMenuItem as MRTActionMenuItem  ,Divider,   , ModeEdit
import { MaterialReactTable, useMaterialReactTable, MRT_ShowHideColumnsButton as ShowHideColumnsButton } from 'material-react-table';
import { getCrmRecordById, usersqlalldata, putdata, getCrmvariables } from "../../util/util";
import { Clear, CopyAll, Search, GetAppOutlined, } from '@mui/icons-material';
import { useSnackbar } from '../customized/SnackbarProvider'; // 导入自定义的 hook
import exportToExcel from '../../util/exportToExcel';
import { MRT_Localization_ZH_HANS as LocalizationZH } from 'material-react-table/locales/zh-Hans';
import { customPrompt } from '../assembly/customprompt'



//合同明细操作

const App = (pagedata) => {
  const [tabledata, setTabledata] = useState([]); // 用于存储获取的数据
  const [searchValue, setSearchValue] = useState(''); // 用于存储输入框的值
  const [isloacked, setIsloacked] = useState(false); // 数据锁定状态
  const [crmdata, setCrmdata] = useState([]); // 用于存储CRM获取的数据
  const [productdata, setProductdata] = useState([]); // 用于存储获取的数据
  // const [deletedata, setDeletedata] = useState([]); // 用于存储删除的数据
  const [rowSelection, setRowSelection] = useState([]); // 用于存储选中的行
  const [loading, setLoading] = useState(true); // 用于控制加载状态
  const [loadingptable, setLoadingptable] = useState(true); // 用于控制加载状态
  const [openDrawer, setOpenDrawer] = useState(false); // 控制抽屉的显示与隐藏
  const [canEdit, setCanEdit] = useState(false); // 控制是否可以编辑

  const openSnackbar = useSnackbar();



  const fetchData = useCallback(async () => {
    try {
      setLoading(true); // 设置加载状态为true
      // console.log("pagedata", pagedata)
      const dataid = pagedata?.data?.EntityId[0];
      const entity = pagedata?.data?.Entity;

      let response = await getCrmvariables("exstuserids");
      let usersex = [];
      if (
        response &&
        response.details &&
        response.details.statusMessage &&
        response.details.statusMessage.variables &&
        Array.isArray(response.details.statusMessage.variables) &&
        response.details.statusMessage.variables.length > 0
      ) {
        let result = response?.details?.statusMessage?.variables[0]?.value;
        console.log("result", result);
        usersex = result.split(",");
      }

      let currentuserinfo = await window.ZOHO.CRM.CONFIG.getCurrentUser(); // 获取当前用户信息
      if (currentuserinfo?.users?.length > 0 && usersex.includes(currentuserinfo?.users[0]?.id)) {
        setCanEdit(true);
      }

      const data = await getCrmRecordById(entity, dataid);
      // console.log("data", data);
      let isloacked = data?.Locked__s || false;
      setIsloacked(isloacked);


      if (data) {
        setCrmdata(data); // 将获取的数据存储到crmdata中
        if (data?.Ordered_Items) {
          let detaildata = data?.Ordered_Items;
          // console.log("detaildata", detaildata);
          const filteredData = detaildata.filter(item =>
            item.Product_Name.id !== "185647000006317039" &&
            item.Product_Name.id !== null
          );
          setTabledata(filteredData); // 将获取的数据存储到tabledata中
        }

      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false); // 数据获取完成后，将加载状态设置为false
    }
  }, [pagedata]);



  useEffect(() => {
    window.ZOHO.CRM.UI.Resize({ height: "100%", width: "100%" })
    fetchData();

  }, [fetchData]);



  //获取产品
  const productsGet = async (searchQuery = "") => {
    setLoadingptable(true);
    try {
      let account = crmdata?.Account_Name?.id;
      // console.log("account", account);
      let sql = `select id,Product_Name,Account.Account_Name,AccountprtNo,ReferenceMaterialNumber1,ReferenceMaterialNumber2,Englishname,Unit_Price,Specification,Productname,Chinesespecification,Category,Classify1,Classify2,internalcode,Lengthofouterbox,Cartonwidth,Heightofouterbox,Volume,Netweightofinnebox,Nuofboxesinpg,Nuofboxeinnerbox,Packagingquantityperpg,Netweight,Grossweight,Unit,Chptrequirements_material,Brand,Packaginunit,Declarationelements,HSCode_text 
      from Products where field1 = '关务部部长审批通过' and Account.id = '${account}'`;
      if (searchQuery) {
        searchQuery = searchQuery.trim();
        sql = `select id,Product_Name,Account.Account_Name,AccountprtNo,ReferenceMaterialNumber1,ReferenceMaterialNumber2,Englishname,Unit_Price,Specification,Productname,Chinesespecification,Category,Classify1,Classify2,internalcode,Lengthofouterbox,Cartonwidth,Heightofouterbox,Volume,Netweightofinnebox,Nuofboxesinpg,Nuofboxeinnerbox,Packagingquantityperpg,Netweight,Grossweight,Unit,Chptrequirements_material,Brand,Packaginunit,Declarationelements,HSCode_text 
        from Products where field1 = '关务部部长审批通过' and (Product_Name like '%${searchQuery}%' or AccountprtNo like '%${searchQuery}%') `;
      }
      let productresult = await usersqlalldata(sql);
      // console.log("productresult", productresult);
      setProductdata(productresult);
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoadingptable(false);
    }
  };
  const saveData = async () => {
    setLoading(true); // 显示加载状态

    try {
      // const dataName = crmdata.Subject;
      const dataid = crmdata.id;
      const olddetaildata = crmdata?.Ordered_Items;

      const missingIds = [];
      if (tabledata.length === 0) {
        openSnackbar("请添加明细！", 'error');
        return;
      };
      olddetaildata.forEach(item1 => {
        const foundItem = tabledata.find(item2 => item1.id === item2.id);

        if (!foundItem) {
          missingIds.push({
            id: item1.id,
            _delete: null
          });
        }
      });

      // console.log(missingIds);
      const updatedArray = [...tabledata, ...missingIds];
      // console.log('updatedArray', updatedArray);
      let requiredarray = []; //记录必填项数组
      let errorRows = [];  //记录箱数不为整数的行
      tabledata.forEach((item, index) => {
        delete item.Sequence_Number;
        let price = item?.List_Price;
        let boxnumber = item?.NumberofCartons;
        let quantity = item?.Quantity;

        if (isNaN(price) || isNaN(boxnumber) || isNaN(quantity) || boxnumber < 0 || quantity < 0) {
          requiredarray.push(index + 1); // Store 1-based index
        }
        if (boxnumber < 0 || boxnumber % 1 !== 0) {
          errorRows.push(index + 1); // Store 1-based index
        }
      });



      if (requiredarray.length > 0) {
        openSnackbar(`第${requiredarray.join(', ')}行箱数、数量、单价不能为空或者0！`, 'error');
        return;
      };

      if (errorRows.length > 0) {
        openSnackbar(`第${errorRows.join(', ')}行箱数不是整数！`, 'error');
        return;
      };

      let datainfojson = {
        "data": [{
          // Subject: dataName,
          "id": dataid,
          // "MainDiscount": crmdata?.MainDiscount,
          "Ordered_Items": updatedArray,
        }],
        "trigger": [
          "workflow"
        ]
      };
      console.log("datainfojson", JSON.stringify(datainfojson));
      // let result_save = await window.ZOHO.CRM.API.upsertRecord({Entity:"Sales_Orders",APIData:datainfojson,duplicate_check_fields:["Subject",],Trigger:["workflow"]});
      let result_save = await putdata("Sales_Orders", datainfojson);
      console.log(result_save);
      await window.ZOHO.CRM.UI.Popup.closeReload();
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);  // 隐藏加载状态
    }
  };


  //产品选择器的列配置
  const columns_product = [
    { accessorKey: 'Product_Name', header: '商品编码', minSize: 100 },
    { accessorKey: 'AccountprtNo', header: '客户货号', minSize: 70 },
    { accessorKey: 'Englishname', header: '英文品名', minSize: 100 },
    { accessorKey: 'Specification', header: '英文规格', minSize: 100 },
    { accessorKey: 'Productname', header: '中文品名', minSize: 100 },
    { accessorKey: 'Chinesespecification', header: '中文规格', minSize: 100 },
    { accessorKey: 'Category', header: '一级类别', minSize: 100 },
    { accessorKey: 'Classify1', header: '二级分类', minSize: 100 },
    { accessorKey: 'Classify2', header: '三级分类', minSize: 100 },
    { accessorKey: 'ReferenceMaterialNumber1', header: '参考料号1', minSize: 100 },
    { accessorKey: 'ReferenceMaterialNumber2', header: '参考料号2', minSize: 100 },
    { accessorKey: 'internalcode', header: '内部货号', minSize: 100 },
    { accessorKey: 'Lengthofouterbox', header: '外箱长(CM)', minSize: 100 },
    { accessorKey: 'Cartonwidth', header: '外箱宽(CM)', minSize: 100 },
    { accessorKey: 'Heightofouterbox', header: '外箱高(CM)', minSize: 100 },
    { accessorKey: 'Volume', header: '外箱体积（CBM）', minSize: 100 },
    { accessorKey: 'Netweightofinnebox', header: '单净重(G)', minSize: 100 },
    { accessorKey: 'Nuofboxesinpg', header: '包装内盒入数', minSize: 100 },
    { accessorKey: 'Nuofboxeinnerbox', header: '包装内盒数', minSize: 100 },
    { accessorKey: 'Packagingquantityperpg', header: '每包装量', minSize: 100 },
    { accessorKey: 'Netweight', header: '外箱净重(KG)', minSize: 100 },
    { accessorKey: 'Grossweight', header: '外箱毛重(KG)', minSize: 100 },
    { accessorKey: 'Unit', header: '单位', minSize: 100 },
    { accessorKey: 'Chptrequirements_material', header: '中文生产要求(材质)', minSize: 100 },
    { accessorKey: 'Brand', header: '品牌报关', minSize: 100 },
    { accessorKey: 'Packaginunit', header: '包装单位', minSize: 100 },
    { accessorKey: 'Declarationelements', header: '申报要素', minSize: 100 },
    { accessorKey: 'HSCode_text', header: 'HSCode', minSize: 100 },
  ];


  const totalNumberofCartons = useMemo(
    () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.NumberofCartons || 0)), 0),
    [tabledata], // 确保在 data 变化时重新计算
  );
  const totalQuantity = useMemo(
    () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.Quantity || 0)), 0),
    [tabledata], // 确保在 data 变化时重新计算
  );
  const totalTotal = useMemo(
    () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.Total || 0)), 0),
    [tabledata], // 确保在 data 变化时重新计算
  );
  const totalfield2 = useMemo(
    () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.field2 || 0)), 0),
    [tabledata], // 确保在 data 变化时重新计算
  );
  const totalfield = useMemo(
    () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.field || 0)), 0),
    [tabledata], // 确保在 data 变化时重新计算
  );
  const totalfield1 = useMemo(
    () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.field1 || 0)), 0),
    [tabledata], // 确保在 data 变化时重新计算
  );

  const totalNet_Total = useMemo(
    () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.Net_Total || 0)), 0),
    [tabledata], // 确保在 data 变化时重新计算
  );

  // const totalDomesticOrderAmount = useMemo(
  //   () => tabledata.reduce((acc, curr) => parseFloat(acc) + parseFloat((curr.DomesticOrderAmount || 0)), 0),
  //   [tabledata], // 确保在 data 变化时重新计算
  // );

  const afdisAmount = useMemo(
    () => (totalNet_Total / 100 * (crmdata?.MainDiscount || 0)).toFixed(3),
    [crmdata, totalNet_Total], // 确保在 data 变化时重新计算
  );

  // const calculxg = useMemo(() => {
  //   // 这里对 tabledata 的每一行进行计算
  //   return tabledata.map((row) => {
  //     const calculatedValue = row['Englishname'] ? row['Englishname'].toUpperCase() : '';

  //     // 返回一个新对象或更新后的行数据
  //     return {
  //       ...row,
  //       calculatedEnglishname: calculatedValue, // 你可以将计算结果保存到新字段
  //     };
  //   });
  // }, [tabledata]); // 依赖项是 tabledata，当 tabledata 变化时重新计算

  //子表列配置
  const columns = useMemo(() => [
    { accessorKey: 'Product_Name.name', header: '商品库名称', minSize: 100, enableEditing: false, },
    {
      accessorKey: 'AccountprtNo', header: '客户货号', minSize: 120, size: 120, enableEditing: canEdit,
      muiEditTextFieldProps: ({ cell, row }) => ({
        type: 'text',
        onBlur: (event) => {
          const value = event.target.value || "";
          const index = cell.row.index;
          tabledata[index]['AccountprtNo'] = value;
          const newTableData = [...tabledata];
          setTabledata(newTableData);
        },
      }),
    },
    {
      accessorKey: 'ShippingMark', header: '唛头', minSize: 100, size: 100, enableEditing: true,
      muiEditTextFieldProps: ({ cell, column, row, table }) => ({
        type: 'text',
        onBlur: (event) => {
          tabledata[row.index][column.id] = event.target.value || "";
          setTabledata([...tabledata]); // 更新表格数据
        },
      })
    },
    { accessorKey: 'internalcode', header: '内部代码', minSize: 120, size: 120, enableEditing: false, },
    {
      accessorKey: 'Englishname', header: '英文品名', minSize: 120, size: 120, enableEditing: true,
      muiEditTextFieldProps: ({ cell, row, table }) => ({
        onBlur: (event) => {
          const index = cell.row.index;
          // console.log("row.original.Englishname",row.original.Englishname);
          // console.log("event.target.value",event.target.value);
          // console.log("row.original.Englishname",row.original.Product_Name.id);
          // const costids = ["185647000006804190"];
          let category = row.original?.Category || '';
          if (category === '费用类' || canEdit) {
            tabledata[index]['Englishname'] = event.target.value;
          } else {
            tabledata[index]['Englishname'] = row.original?.Englishname;
          }
          const newTableData = [...tabledata];
          setTabledata(newTableData);
        },
      }),
    },
    { accessorKey: 'Specification', header: '英文规格', minSize: 100, enableEditing: false, },
    {
      accessorKey: 'List_Price', header: '单价', minSize: 90, size: 90, enableEditing: true, required: true,
      muiEditTextFieldProps: ({ cell, row }) => ({
        type: 'number',
        required: true, // 设置必填
        onBlur: (event) => {
          const value = parseFloat(event.target.value) || 0; // Ensure it's a number
          const index = cell.row.index;
          tabledata[index]['List_Price'] = value;

          let qty = tabledata[index]['Quantity'] || 0;
          let total = (value * qty);
          tabledata[index]['Total'] = total.toFixed(2);

          let discount_b = tabledata[index]['ItemDiscountRate'] || 0;
          let discount = -(total / 100 * discount_b);
          tabledata[index]['Discount'] = discount.toFixed(2);

          tabledata[index]['Net_Total'] = (parseFloat(total) + parseFloat(discount)).toFixed(2);
          // tabledata[index]['DomesticOrderAmount'] = (total * (100 - crmdata.RetentionRate) / 100).toFixed(2);
          const newTableData = [...tabledata];
          setTabledata(newTableData); // Trigger re-render
        },
      }),
    },
    {
      accessorKey: 'Quantity', header: '数量', minSize: 90, size: 90, enableEditing: true, required: true,
      muiEditTextFieldProps: ({ cell, row, table }) => ({
        type: 'number',
        required: true, // 设置必填
        onBlur: (event) => {
          // console.log(table); // 打印表格实例
          // console.log(row); // 打印表格实例
          // console.log(table.getAllColumns()); // 打印表格实例
          const value = parseFloat(event.target.value); // Ensure it's a number
          // if (isNaN(value)) return; // Handle non-numeric input

          const index = cell.row.index;
          let qty = value || 0;
          tabledata[index]['Quantity'] = qty;

          // Calculate other fields based on the new quantity
          let boxnum = (qty / (tabledata[index]['Packagingquantityperpg'] || 1));
          tabledata[index]['NumberofCartons'] = boxnum.toFixed(2);
          tabledata[index]['field'] = (tabledata[index]['Volume'] * boxnum).toFixed(4);
          tabledata[index]['field1'] = (tabledata[index]['Grossweight'] * boxnum).toFixed(4);
          tabledata[index]['field2'] = (tabledata[index]['Netweight'] * boxnum).toFixed(4);

          let total = (qty * (tabledata[index]['List_Price'] || 0));
          tabledata[index]['Total'] = total.toFixed(2);

          let discount_b = tabledata[index]['ItemDiscountRate'] || 0;
          let discount = -(total / 100 * discount_b);
          tabledata[index]['Discount'] = discount.toFixed(2);

          let nettotal = (parseFloat(total) + parseFloat(discount)).toFixed(2);
          tabledata[index]['Net_Total'] = nettotal;
          // tabledata[index]['DomesticOrderAmount'] = (nettotal * (100 - crmdata.RetentionRate) / 100).toFixed(2);
          const newTableData = [...tabledata];
          setTabledata(newTableData);
        },
      }),
      Footer: () => (
        <Stack>
          <Box color="warning.main">{totalQuantity.toFixed(3)}</Box>
        </Stack>
      ),
    },
    {
      accessorKey: 'NumberofCartons', header: '箱数', minSize: 90, size: 90, enableEditing: true, required: false,
      muiEditTextFieldProps: ({ cell, row }) => ({
        type: 'number',
        required: true, // 设置必填
        onBlur: (event) => {
          const boxnum = parseFloat(event.target.value) || 0; // Ensure it's a number

          const index = cell.row.index;
          tabledata[index]['NumberofCartons'] = boxnum;

          // Calculate other fields based on the new quantity
          let qty = boxnum * (tabledata[index]['Packagingquantityperpg'] || 1).toFixed(0);
          tabledata[index]['Quantity'] = qty;
          tabledata[index]['field'] = (tabledata[index]['Volume'] * boxnum).toFixed(4);
          tabledata[index]['field1'] = (tabledata[index]['Grossweight'] * boxnum).toFixed(4);
          tabledata[index]['field2'] = (tabledata[index]['Netweight'] * boxnum).toFixed(4);

          let total = (qty * (tabledata[index]['List_Price'] || 0)).toFixed(2);
          tabledata[index]['Total'] = total;


          let discount_b = tabledata[index]['ItemDiscountRate'] || 0;
          let discount = -(total / 100 * discount_b);

          let nettotal = (parseFloat(total) + parseFloat(discount)).toFixed(2);
          tabledata[index]['Net_Total'] = nettotal;
          tabledata[index]['Discount'] = discount.toFixed(2);

          // tabledata[index]['DomesticOrderAmount'] = (nettotal * (100 - crmdata.RetentionRate) / 100).toFixed(2);
          const newTableData = [...tabledata];

          setTabledata(newTableData);
        },
      }),
      Footer: () => (
        <Stack>
          <Box color="warning.main">{Math.round(totalNumberofCartons)}</Box>
        </Stack>
      ),
    },
    { accessorKey: 'Packagingquantityperpg', header: '每箱装量', minSize: 110, size: 110, enableEditing: false, },
    {
      accessorKey: 'Total', header: '金额', minSize: 90, size: 90, enableEditing: false,
      Footer: () => (
        <Stack>
          <Box color="warning.main">{totalTotal.toFixed(3)}</Box>
        </Stack>
      ),
    },
    {
      accessorKey: 'ItemDiscountRate', header: '单品折扣率', minSize: 140, size: 140, enableEditing: true,
      muiEditTextFieldProps: ({ cell, row }) => ({
        type: 'number',
        onBlur: (event) => {
          const value = parseFloat(event.target.value || 0);
          const index = cell.row.index;
          let total = tabledata[index]['Total'] || 0;
          let discount = -(total / 100 * value);
          tabledata[index]['ItemDiscountRate'] = value;
          tabledata[index]['Discount'] = discount.toFixed(2);
          tabledata[index]['Net_Total'] = (parseFloat(total) + parseFloat(discount || 0)).toFixed(2);
          setTabledata([...tabledata]);
        },
      }),
    },
    {
      accessorKey: 'Discount', header: '单品折扣', minSize: 140, size: 140, enableEditing: true,
      muiEditTextFieldProps: ({ cell, row }) => ({
        type: 'number',
        onBlur: (event) => {
          const value = parseFloat(event.target.value || 0);

          const index = cell.row.index;
          let total = tabledata[index]['Total'] || 0;
          let itemDiscountRate = (-value / (total * 100 || 1)).toFixed(2);
          tabledata[index]['Discount'] = value;
          tabledata[index]['ItemDiscountRate'] = itemDiscountRate;
          tabledata[index]['Net_Total'] = (parseFloat(tabledata[index]['Total'] || 0) + value).toFixed(2);
          setTabledata([...tabledata]);
        },
      }),
    },
    {
      accessorKey: 'Net_Total', header: '折扣后金额', minSize: 120, size: 120, enableEditing: true,
      muiEditTextFieldProps: ({ cell, column, row, table }) => ({
        type: 'text',
        onBlur: (event) => {
          tabledata[row.index][column.id] = event.target.value || "";
          setTabledata([...tabledata]); // 更新表格数据
        },
      }),
      Footer: () => (
        <Stack>
          <Box color="warning.main">{`${totalNet_Total.toFixed(3)} - ${(parseFloat(afdisAmount || 0)).toFixed(3)} = ${(totalNet_Total - afdisAmount).toFixed(3)}`}</Box>
        </Stack>
      ),
    },
    // {
    //   accessorKey: 'DomesticOrderAmount', header: '国内接单金额', minSize: 140, size: 140, enableEditing: true,
    //   muiEditTextFieldProps: ({ cell, row }) => ({
    //     type: 'number',
    //     required: true, // 设置必填
    //     onBlur: (event) => {
    //       const value = parseFloat(event.target.value) || 0; // Ensure it's a number
    //       const index = cell.row.index;
    //       tabledata[index]['DomesticOrderAmount'] = value.toFixed(2);
    //       setTabledata([...tabledata]);
    //     },
    //   }),
    //   Footer: () => (
    //     <Stack>
    //       <Box color="warning.main">{`${totalDomesticOrderAmount.toFixed(3)} - ${(parseFloat(afdisAmount || 0)).toFixed(3)} = ${(totalDomesticOrderAmount - afdisAmount).toFixed(3)}`}</Box>
    //     </Stack>
    //   ),
    // },
    { accessorKey: 'Unit', header: '单位', minSize: 90, size: 90, enableEditing: false, },
    { accessorKey: 'Brand', header: '品牌', minSize: 90, size: 90, enableEditing: false, },
    { accessorKey: 'Nuofboxesinpg', header: '入数', minSize: 90, size: 90, enableEditing: false, },
    { accessorKey: 'Nuofboxeinnerbox', header: '内盒数', minSize: 100, size: 100, enableEditing: false, },
    { accessorKey: 'Lengthofouterbox', header: '长(CM)', minSize: 100, size: 100, enableEditing: false, },
    { accessorKey: 'Cartonwidth', header: '宽(CM)', minSize: 100, size: 100, enableEditing: false, },
    { accessorKey: 'Heightofouterbox', header: '高(CM)', minSize: 100, size: 100, enableEditing: false, },
    { accessorKey: 'Volume', header: '体积', minSize: 100, size: 100, enableEditing: false, },
    { accessorKey: 'Netweight', header: '净重(KG)', minSize: 110, size: 110, enableEditing: false, },
    { accessorKey: 'Grossweight', header: '毛重(KG)', minSize: 110, size: 110, enableEditing: false, },
    {
      accessorKey: 'field2', header: '总净重', minSize: 110, size: 110, enableEditing: false,
      Footer: () => (
        <Stack>
          <Box color="warning.main">{totalfield2.toFixed(4)}</Box>
        </Stack>
      ),
    },
    {
      accessorKey: 'field1', header: '总毛重', minSize: 110, size: 110, enableEditing: false,
      // Cell: ({ row }) => {
      //   const total = ((row.original.NumberofCartons || 0) * (row.original.Grossweight || 0));
      //   return total.toFixed(2);
      // },
      Footer: () => (
        <Stack>
          <Box color="warning.main">{totalfield1.toFixed(4)}</Box>
        </Stack>
      ),
    },
    {
      accessorKey: 'field', header: '总体积', minSize: 110, size: 110, enableEditing: false,
      Footer: () => (
        <Stack>
          <Box color="warning.main">{totalfield.toFixed(4)}</Box>
        </Stack>
      ),
    },
    { accessorKey: 'Productname', header: '中文品名', minSize: 100, enableEditing: false, },
    { accessorKey: 'ChinesePackagedesp', header: '中文包装描述', minSize: 100, enableEditing: false, },
    { accessorKey: 'Chinesespecification', header: '中文规格', minSize: 100, enableEditing: false, },
    // { accessorKey: 'Chineseingredients', header: '中文成份', minSize: 100, enableEditing: false, },
    { accessorKey: 'Chptrequirements_material', header: '中文生产要求(材质)', minSize: 180, enableEditing: false, },
    { accessorKey: 'Category', header: '类别', minSize: 100, size: 100, enableEditing: false, },
    { accessorKey: 'Packaginunit', header: '包装单位', minSize: 120, size: 120, enableEditing: false, },
    { accessorKey: 'HSCode', header: 'HS编码', minSize: 120, size: 120, enableEditing: false, },
    {
      accessorKey: 'field3', header: '商品备注', minSize: 120, size: 120, enableEditing: true,
      muiEditTextFieldProps: ({ cell, row }) => ({
        type: 'text',
        required: true, // 设置必填
        onBlur: (event) => {
          const value = event.target.value || ""; // Ensure it's a number
          const index = cell.row.index;
          tabledata[index]['field3'] = value;
          setTabledata([...tabledata]);
        },
      }),
    },
  ], [tabledata, canEdit, totalNumberofCartons, totalQuantity, totalTotal, totalfield2, totalfield, totalfield1, afdisAmount, totalNet_Total]);

  const cpfn = async () => {
    try {
      setLoading(true);
      const userInput = await customPrompt("1、多个号码用逗号或换行符分隔;  2、不能超过50个编号;  3、可以输入客户货号和产品编号");
      if (!userInput && userInput.trim() === '') {
        openSnackbar('请输入有效值！', 'warning');
        return;
      }
      const codearray = userInput.split(/[\s,|\n]+/).filter(item => item.trim() !== '');

      if (codearray.length === 0) {
        openSnackbar('请输入有效值！', 'warning');
        return;
      } else if (codearray.length > 50) {
        openSnackbar('不能超过50个！', 'warning');
        return;
      }

      const formattedCodes = codearray.map(code => `'${code.trim()}'`).join(',');
      let sql = `select id,Product_Name,Account.Account_Name,AccountprtNo,ReferenceMaterialNumber1,ReferenceMaterialNumber2,Englishname,Unit_Price,Specification,Productname,Chinesespecification,Category,Classify1,Classify2,internalcode,Lengthofouterbox,Cartonwidth,Heightofouterbox,Volume,Netweightofinnebox,Nuofboxesinpg,Nuofboxeinnerbox,Packagingquantityperpg,Netweight,Grossweight,Unit,Chptrequirements_material,Brand,Packaginunit,Declarationelements,HSCode_text 
    from Products where Product_Name in (${formattedCodes}) or AccountprtNo in (${formattedCodes})`;
      console.log(sql);
      let productresult = await usersqlalldata(sql);
      console.log(productresult);
      if (productresult) {
        let resultarray = [];
        productresult.forEach((product) => {

          const findprid = tabledata.find((item) => item.Product_Name.id === product.id);

          // console.log(findprid);
          if (!findprid) {
            resultarray.push({
              Product_Name: { id: product.id, name: product.Product_Name }, // 产品名称
              Product_Id: product.id, // 产品ID
              AccountprtNo: product.AccountprtNo,
              ShippingMark: product.ShippingMark,
              internalcode: product.internalcode,
              Englishname: product.Englishname,
              Specification: product.Specification,
              List_Price: product.Unit_Price,        // 价格
              // Discount: (product.Unit_Price || 0),       //crmdata?.MainDiscount || 0,
              // DomesticOrderAmount: product.AccountprtNo,
              // Quantity: product.AccountprtNo,
              // Total: product.AccountprtNo,
              // Net_Total: product.AccountprtNo,
              // NumberofCartons: product.AccountprtNo,
              Packagingquantityperpg: product?.Packagingquantityperpg,  //每包装量
              Unit: product.Unit,
              Brand: product.Brand,
              Nuofboxesinpg: product.Nuofboxesinpg,
              Nuofboxeinnerbox: product.Nuofboxeinnerbox,
              Lengthofouterbox: product.Lengthofouterbox,
              Cartonwidth: product.Cartonwidth,
              Heightofouterbox: product.Heightofouterbox,
              Volume: product.Volume,
              Netweight: product.Netweight,
              Grossweight: product.Grossweight,
              // field2: product.AccountprtNo,
              // field1: product.AccountprtNo,
              // field: product.AccountprtNo,
              Productname: product.Productname,
              ChinesePackagedesp: product.ChinesePackagedesp,
              Chinesespecification: product.Chinesespecification,
              Chineseingredients: product.Chineseingredients,
              Chptrequirements_material: product.Chptrequirements_material,
              Category: product.Category,
              Packaginunit: product.Packaginunit,
              HSCode: product.HSCode_text,
              // field3: product.AccountprtNo,

            });
          }
        })
        // 将选中的产品添加到主表中
        setTabledata((prevData) => [...prevData, ...resultarray]);
        setLoading(false);
      } else {
        openSnackbar('未找到商品！', 'warning');
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  }
  //子表配置
  const table = useMaterialReactTable({
    columns: columns,
    data: tabledata ?? [],
    enableRowOrdering: true, // 行排序
    enablePagination: false, // 禁用分页
    enableColumnOrdering: true, // 列排序
    enableColumnFilters: false, // 列过滤
    enableStickyHeader: true, // 启用粘性表头
    enableGlobalFilter: false, // 禁用全局过滤
    enableColumnResizing: true, // 启用列调整大小
    editDisplayMode: 'cell', // 编辑模式为单元格
    enableEditing: true,  // 启用编辑
    localization: LocalizationZH, // 设置中文
    enableDensityToggle: false, // 禁用密度切换
    // enableRowOrdering: true, // 启用行排序
    enableSorting: false, // 禁用排序
    enableFullScreenToggle: false, // 禁用全屏按钮
    enableColumnPinning: true, // 启用列固定
    // getRowId: (row) => row.Product_Name.id, // 设置每行的唯一标识
    positionToolbarAlertBanner: 'bottom',   // 将工具栏警告横幅的位置设置为底部
    layoutMode: 'grid-no-grow', // 设置布局模式为网格，并且不增长
    initialState: {
      density: 'compact',
      columnPinning: { left: ['mrt-row-drag', 'mrt-row-actions', 'mrt-row-numbers', 'Product_Name.name', 'AccountprtNo', 'internalcode'] },  //'mrt-row-actions',
    },
    muiTableContainerProps: {
      sx: {
        minHeight: '75vh', // 这里设置表格最大高度
        maxHeight: '75vh', // 这里设置表格最大高度
        overflowY: 'auto',  // 启用竖向滚动条
        overflowX: 'auto',  // 启用横向滚动条，横向滚动条默认显示
      },
    },
    muiTableHeadCellProps: ({ column }) => ({
      sx: {
        backgroundColor: 'rgb(244, 247, 255)',
        ...(column.columnDef.required && {
          '&::after': {
            content: '"*"',
            color: 'red',
            marginLeft: '30px',
            position: 'absolute',
          }
        })
      }
    }),
    muiRowDragHandleProps: ({ table }) => ({
      onDragEnd: () => {
        const { draggingRow, hoveredRow } = table.getState();
        if (hoveredRow && draggingRow) {
          tabledata.splice(
            hoveredRow.index,
            0,
            tabledata.splice(draggingRow.index, 1)[0],
          );
          setTabledata([...tabledata]);
        }
      },
    }),
    enableRowNumbers: true,
    rowNumberDisplayMode: 'static', // 显示原始行号
    renderTopToolbarCustomActions: ({ table }) => (
      <Box sx={{ display: 'flex', gap: '1rem', p: '4px' }}>
        <Button
          // color="primary"
          onClick={() => {
            setOpenDrawer(true); // 打开抽屉
            productsGet(); // 获取商品库数据
          }}
          variant="contained"
          disabled={isloacked}
        >
          从商品库选取
        </Button>
        <Button
          // color="primary"
          onClick={async () => {
            await saveData(); // 保存数据
          }}
          variant="contained"
          disabled={isloacked}
        >
          保存
        </Button>
        <Button
          onClick={cpfn}
          variant="contained"
        >
          从剪贴板添加
        </Button>
        {/* <Button
          onClick={async () => {
            const userInput = await customPrompt("请输入一个有效数字");
            const isValid = userInput !== "" && /^[1-9]\d*$/.test(userInput);
            if (isValid) {
              tabledata.forEach((item) => {
                item.Quantity = userInput;
              });
              setTabledata([...tabledata]);
            } else {
              openSnackbar("请输入一个有效数字", "error");
            }

          }}
          variant="contained"
        >
          批量修改数量
        </Button> */}
        <Button
          onClick={() => {
            window.ZOHO.CRM.UI.Popup.close();
          }}
          variant="outlined"
        >
          取消
        </Button>
      </Box>
    ),
    enableRowActions: true,
    displayColumnDefOptions: {
      'mrt-row-actions': {
        header: '操作',  // 设置表头为“操作”
        size: 4,  // 设置列宽
      },
      'mrt-row-drag': {
        header: '',  // 设置表头为“操作”
        size: 4,  // 设置列宽
      },
    },
    renderRowActions: ({ row, table }) => (
      <Box>
        <Clear
          onClick={() => {
            if (!isloacked) {
              // setTabledata((prevRecords) => prevRecords.filter((record) => record.Product_Name.id !== row.id)); // 从记录中移除当前行
              tabledata.splice(row.index, 1); //assuming simple data table
              setTabledata([...tabledata]);
            }
          }}>
        </Clear>
        <CopyAll onClick={() => {
          if (!isloacked) {
            const newRow = { ...row.original }; // 生成新的 ID
            console.log(newRow);
            delete newRow.id;
            delete newRow.WItemId;
            delete newRow.PSQty;
            delete newRow.SNQty;

            // 复制当前行数据
            // const newRow = { ...row.original, id: `${Date.now()}new` }; // 生成新的 ID
            // 插入到当前数据下面
            // const index = table.getRowModel().rows.findIndex(r => r.id === row.id);
            // const newData = [
            //   ...tabledata.slice(0, index + 1),
            //   newRow,
            //   ...tabledata.slice(index + 1)
            // ];
            // 将新数据插入到最后一行
            const newData = [...tabledata, newRow];
            setTabledata(newData); // 更新数据
          }
        }}>
        </CopyAll>
      </Box>
    ),
    // muiEditTextFieldProps: ({ cell }) => ({
    //   onBlur: (event) => {
    //     handleSaveCell(cell, event.target.value); // 在失焦时保存
    //   },
    // }),
    renderToolbarInternalActions: ({ table }) => (
      <Box>
        <IconButton
          onClick={() => {
            if (tabledata && tabledata.length > 0) {
              exportToExcel(tabledata, columns); // 导出数据到Excel
            } else {
              openSnackbar(`没有数据可以导出`, 'info');
            }
          }}
        >
          <GetAppOutlined />
        </IconButton>
        <ShowHideColumnsButton table={table} />
      </Box>
    ),
    enableKeyboardShortcuts: false,
    defaultColumn: {
      muiTableBodyCellProps: ({ row, cell }) => ({
        onKeyDown: (event) => { // 添加键盘事件监听
          if (event.key === 'Enter') {
            const nextrownum = row.index + 1; // 获取下一行的索引
            const currentIndex = cell.column.getIndex();
            if (nextrownum < tabledata.length) {
              const nextRow = document.querySelector(
                `tr[data-index="${nextrownum}"]`
              );

              // 在该行中找到对应列的单元格
              if (nextRow) {
                const nextCell = nextRow.querySelector(
                  `td[data-index="${currentIndex}"]`
                );
                if (nextCell) {
                  nextCell.focus();
                  const dblClickEvent = new MouseEvent('dblclick', {
                    bubbles: true,
                    cancelable: true,
                    view: window
                  });
                  nextCell.dispatchEvent(dblClickEvent);
                }
              }
            }
          }
        },
        tabIndex: 0,
      })
    },
    // enableCellActions: true, // 启用单元格操作
    // enableClickToCopy: "context-menu", // 启用点击复制
    // renderCellActionMenuItems: ({ closeMenu, table, column, row, internalMenuItems }) => [
    //   ...internalMenuItems,
    //   <Divider key="divider" />,
    // <MRTActionMenuItem
    //   icon={<ContentCopyOutlined />}
    //   key={1}
    //   label="复制整列"
    //   onClick={(e) => {
    //     const columnid = column?.id;
    //     const rownum = row?.index;
    //     if (columnid !== undefined && rownum !== undefined) {
    //       // 从 table 中获取所有数据
    //       const allRows = table.getRowModel().rows;

    //       // 过滤数据从指定的 rownum 开始
    //       const filteredRows = allRows.slice(rownum);

    //       // 获取 columnid   对应列的数据
    //       const columnData = filteredRows.map((row) => row.getValue(columnid));

    //       // 将数据用制表符或回车隔开
    //       const newlineSeparatedData = columnData.join('\n');

    //       console.log('回车分隔数据:', newlineSeparatedData);
    //       // 复制数据到剪贴板 (使用制表符分隔数据)
    //       navigator.clipboard.writeText(newlineSeparatedData)
    //         .then(() => {
    //           console.log('数据已成功复制到剪贴板');
    //         })
    //         .catch((err) => {
    //           console.error('复制到剪贴板失败:', err);
    //         });
    //     }

    //     closeMenu();
    //   }}
    //   table={table}
    // />,
    //   <MRTActionMenuItem
    //     icon={<ModeEdit />}
    //     key={2}
    //     label="批量修改整列"
    //     onClick={async () => {
    //       const columnid = column?.id;
    //       const rownum = row?.index;
    //       // console.log(columnid, rownum);
    //       if (columnid !== undefined && rownum !== undefined) {
    //         const userInput = await customPrompt("请输入值:");
    //         console.log(userInput);

    //         tabledata.forEach((row, index) => {
    //             tabledata[index][columnid] = userInput;
    //         })

    //         const newTableData = [...tabledata];
    //         setTabledata(newTableData); 
    //         console.log(tabledata); // 更新表格数据
    //       }
    //       // 从剪贴板读取数据
    //       closeMenu();
    //     }}
    //     table={table}
    //   />,
    // ],
  });


  //产品选择配置
  const table_product = useMaterialReactTable({
    columns: columns_product,
    data: productdata || [],
    enableColumnResizing: true, // 启用列调整大小
    enableStickyHeader: true, // 启用粘性表头
    enableDensityToggle: false, // 禁用密度切换
    enableGlobalFilter: false, // 禁用全局过滤
    state: {
      rowSelection, // 设置行选择状态
      isLoading: loadingptable,     // 设置加载状态
    },
    enableFullScreenToggle: false, // 禁用全屏按钮
    enableColumnPinning: true, // 启用列固定
    localization: LocalizationZH, // 设置中文
    getRowId: (row) => row.id, // 设置每行的唯一标识
    // rowPinningDisplayMode: 'select-sticky', // 设置行固定显示模式为选择固定
    positionToolbarAlertBanner: 'bottom',   // 将工具栏警告横幅的位置设置为底部
    initialState: {
      density: 'compact',
      columnPinning: { left: ['mrt-row-select', 'mrt-row-numbers', 'Product_Name', 'AccountprtNo'] },
      pagination: { pageSize: 20, },
      showColumnFilters: true, // 显示列过滤器
      columnVisibility: { Lengthofouterbox: false, Cartonwidth: false, Heightofouterbox: false, Volume: false, Netweightofinnebox: false, Nuofboxesinpg: false, Nuofboxeinnerbox: false, Packagingquantityperpg: false, Netweight: false, Grossweight: false, Packaginunit: false, Declarationelements: false, HSCode_text: false, }
    },
    muiTableContainerProps: {
      sx: {
        minHeight: '75vh', // 这里设置表格最大高度
        maxHeight: '75vh', // 这里设置表格最大高度
        overflowY: 'auto',  // 启用竖向滚动条
        overflowX: 'auto',  // 启用横向滚动条，横向滚动条默认显示
      },
    },
    // enableRowNumbers: true,
    // rowNumberDisplayMode: 'static', // 显示原始行号
    enableRowSelection: true,   // 启用行选择
    onRowSelectionChange: setRowSelection, // 当行选择发生变化时，更新行选择状态
    renderTopToolbarCustomActions: ({ table }) => (
      <Box sx={{ display: 'flex', gap: '1rem', p: '4px' }}>
        <TextField
          placeholder="请输入商品编码或者客户货号的关键字进行搜索" // 设置搜索框的占位符
          variant="outlined"  // 使用 Material-UI 的 outlined 风格
          size="small"        // 设置搜索框的尺寸
          value={searchValue} // 绑定搜索框的值到 searchValue 变量
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton
                  onClick={() => {
                    productsGet(searchValue); // 调用搜索函数
                  }}
                >
                  <Search />
                </IconButton>
              </InputAdornment>
            ),
            onChange: (e) => {
              setSearchValue(e.target.value);
            }, // 添加 onChange 事件处理函数
            sx: {
              width: '100%', // 设置输入框宽度为100%
              borderRadius: '6px', // 设置圆角
              backgroundColor: '#f5f7f8', // 背景颜色
            },
          }}
          sx={{ width: '400px' }} // 设置搜索框宽度
        />
        <Button
          onClick={() => {
            // 从选中的行中提取产品信息
            const selectedProductIds = Object.keys(rowSelection).filter((key) => rowSelection[key]); // 获取选中的产品 ID
            if (selectedProductIds.length === 0) {
              openSnackbar(`请选择至少一个产品！`, 'info');
              return;
            }
            const selectedProducts = selectedProductIds.map((id) => {
              const selectedRow = productdata.find((product) => product.id === id); // 获取选中的产品
              return selectedRow; // 返回选中的产品信息
            }).filter(Boolean); // 过滤掉未找到的产品

            let resultarray = [];
            selectedProducts.forEach((product) => {

              const findprid = tabledata.find((item) => item.Product_Name.id === product.id);

              // console.log(findprid);
              if (!findprid) {
                resultarray.push({
                  Product_Name: { id: product.id, name: product.Product_Name }, // 产品名称
                  Product_Id: product.id, // 产品ID
                  AccountprtNo: product.AccountprtNo,
                  ShippingMark: product.ShippingMark,
                  internalcode: product.internalcode,
                  Englishname: product.Englishname,
                  Specification: product.Specification,
                  List_Price: product.Unit_Price,        // 价格
                  // Discount: (product.Unit_Price || 0),       //crmdata?.MainDiscount || 0,
                  // DomesticOrderAmount: product.AccountprtNo,
                  // Quantity: product.AccountprtNo,
                  // Total: product.AccountprtNo,
                  // Net_Total: product.AccountprtNo,
                  // NumberofCartons: product.AccountprtNo,
                  Packagingquantityperpg: product?.Packagingquantityperpg,  //每包装量
                  Unit: product.Unit,
                  Brand: product.Brand,
                  Nuofboxesinpg: product.Nuofboxesinpg,
                  Nuofboxeinnerbox: product.Nuofboxeinnerbox,
                  Lengthofouterbox: product.Lengthofouterbox,
                  Cartonwidth: product.Cartonwidth,
                  Heightofouterbox: product.Heightofouterbox,
                  Volume: product.Volume,
                  Netweight: product.Netweight,
                  Grossweight: product.Grossweight,
                  // field2: product.AccountprtNo,
                  // field1: product.AccountprtNo,
                  // field: product.AccountprtNo,
                  Productname: product.Productname,
                  ChinesePackagedesp: product.ChinesePackagedesp,
                  Chinesespecification: product.Chinesespecification,
                  Chineseingredients: product.Chineseingredients,
                  Chptrequirements_material: product.Chptrequirements_material,
                  Category: product.Category,
                  Packaginunit: product.Packaginunit,
                  HSCode: product.HSCode_text,
                  // field3: product.AccountprtNo,

                });
              }
            })


            // console.log(resultarray);

            // 将选中的产品添加到主表中
            setTabledata((prevData) => [...prevData, ...resultarray]);

            // 可选：清空行选择状态
            setRowSelection({});


          }}
          variant="contained"
          sx={{
            backgroundColor: 'rgb(74, 146, 243)', // 背景颜色设置为白色
          }}
        >
          添加产品
        </Button>
        <Button
          onClick={() => {
            setOpenDrawer(false); // 关闭抽屉组件
          }}
          variant="contained"
          sx={{
            backgroundColor: '#ffffff', // 背景颜色设置为白色
            color: '#000000', // 字体颜色设置为黑色
          }}
        >
          我已经选取完成了
        </Button>
      </Box>
    ),
  });

  return (
    <>
      <div>
        {loading ? (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              height: '100vh', // 使加载图标在页面中央
              bgcolor: 'background.default',
            }}
          >
            <CircularProgress />
          </Box>
        ) : (
          <>
            <Grid direction="row"
              container spacing={2}
              sx={{
                justifyContent: "flex-start",
                alignItems: "flex-start",
              }}>
              <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="编号"
                  value={crmdata?.Subject || ''}
                  size="small"
                />
              </Grid>
              <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="客户订单号"
                  value={crmdata?.AccountOrderNo || ''}
                  size="small"
                />
              </Grid>
              <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="合同日期"
                  value={crmdata?.ContractDate || ''}
                  size="small"
                />
              </Grid>
              <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="发货人代码"
                  value={crmdata?.Header?.name || ''}
                  size="small"
                />
              </Grid>
              <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="客户"
                  value={crmdata?.Account_Name?.name || ''}
                  size="small"
                />
              </Grid>
              {/* <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="香港留点比例"
                  value={crmdata?.RetentionRate || ''}
                  // onChange={(e) => setCrmdata((prevData) => ({ ...prevData, RetentionRate: e.target.value }))}
                  size="small"
                />
              </Grid> */}
              <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="合同总折扣%"
                  value={crmdata?.MainDiscount || ''}
                  onChange={(e) => setCrmdata((prevData) => ({ ...prevData, MainDiscount: e.target.value }))}
                  size="small"
                  sx={{ display: 'none' }} // 直接隐藏
                />
              </Grid>
              <Grid item="true" xs={4} md={1}>
                <TextField
                  disabled
                  label="合同总折扣金额"
                  value={afdisAmount || ''} // 这里需要计算
                  size="small"
                  sx={{ display: 'none' }} // 直接隐藏
                />
              </Grid>
            </Grid>
            <MaterialReactTable
              table={table} />
          </>
        )}
      </div>
      {/* 抽屉组件 */}
      <Drawer
        anchor="left"
        open={openDrawer}
        sx={{ width: '75vw', zIndex: 1300 }}
      >
        <Box sx={{ width: '75vw', padding: '2px' }}>
          <MaterialReactTable
            table={table_product}
          />
        </Box>
      </Drawer >


      {/* 批量输入组件 */}


    </>
  );



}



export default App;